<?php

/**
 * Subclass for representing a row from the 'receipt' table.
 *
 * 
 *
 * @package lib.model
 */ 
class Receipt extends BaseReceipt
{
    /**
     * return true, if anonymus user can buy
     */
    public static function isAnonymousCartAllowed()
    {
        $allowed = false;
        if(sfConfig::get('app_cart_allow_anonymous', 0) == 1 )
        {
            $allowed = true;
        }
        return $allowed;
    }
    /**
     * Enter description here...
     *
     * @param unknown_type $userId
     * @return Receipt
     */
    public function getPriceByCurrencyCode($currencyCode = 'LTL')
    {
//        $arConverter = MyConstants::getCurrencyConverter();
//        $currency = $this->getCurrencyCode();
//        $toCurrency = $currencyCode;
//        $factorKey = $currency . '_' . $toCurrency;
        $price = $this->getTotalPrice($currencyCode);
//        if( !empty($arConverter[$factorKey]) && ($arConverter[$factorKey] != $currency) )
//        {
//            $price = $this->getTotalPrice($currencyCode) * $arConverter[$factorKey];
//        }
        return $price / 100;
    }
    /**
     * @return price
     * rewrite BaseReceipt::getTotalPrice(), counts actual price of all receipt items
     */
    public function getTotalPrice($currencyCode = 'LTL')
    {
        $amount = 0;
        $c = new Criteria();
        $c->add(ReceiptItemPeer::RECEIPT_ID, $this->getId());
        $items = ReceiptItemPeer::doSelect($c);
        
        $arConverter = MyConstants::getCurrencyConverter();
        $toCurrency = $currencyCode;
        foreach ($items as $item )
        {
            /* @var $item ReceiptItem */
            $currency = $item->getCurrencyCode();
            $factorKey = $currency . '_' . $toCurrency;
            $price = $item->getPriceOfItem() * $item->getQuantity();
            if( !empty($arConverter[$factorKey]) && ($arConverter[$factorKey] != $currency) )
            {
                $price = $item->getPriceOfItem() * $arConverter[$factorKey] * $item->getQuantity();
            }
            $amount = $amount + $price;
        }
        return $amount;
    }
	/**
     * @return Shipping price
     * rewrite BaseReceipt::getShippingPrice(), counts actual Shipping price
     */
	public function getShippingPrice($currencyCode = 'LTL')
	{
		/* @var $shipping Shipping */
		$price = 0;
		$shipping = ShippingPeer::retrieveByPK($this->getShippingId());
		if($shipping)
		{
			$price = $shipping->getPrice();
			$arConverter = MyConstants::getCurrencyConverter();
			$toCurrency = $currencyCode;
			$currency = $shipping->getCurrency();
			$factorKey = $currency . '_' . $toCurrency;
			if( !empty($arConverter[$factorKey]) && ($arConverter[$factorKey] != $currency) )
            {
                $price = $price * $arConverter[$factorKey];
            }
		}
		return $price;
	}
    /**
     * @return Shipping price
     * rewrite BaseReceipt::getShippingPrice(), counts actual Shipping price minor
     */
	public function getShippingPriceMinor($currencyCode = 'LTL')
	{
		return $this->getShippingPrice($currencyCode)?($this->getShippingPrice($currencyCode) /100) : 0;
	}
    /**
     * when user id <= 0 (anonymus)
     * @param md5 uid
     */
    public static function getOrCreateByAnonymousUid($uid, $createIfEmpty = false )
    {
        $cart = null;
        if( strlen($uid) < 1 )
        {
            throw new Exception('User uid not set.');
        }
        $c = new Criteria();
        $c->add(ReceiptPeer::UID, $uid);
        $c->add(ReceiptPeer::STATUS_ID, MyConstants::STATUS_NEW);
        $cart = ReceiptPeer::doSelectOne($c);
        if(empty($cart ) && $createIfEmpty)
        {
            $cart = new Receipt();
            $cart->setUserId(0);
            $cart->setUid($uid);
            $cart->setStatusId(MyConstants::STATUS_NEW);
            $cart->save();
        }
        return $cart;
    }
    /**
     *  returns true if receipt exists
     * @return boolean
     */
    public static function receiptExist()
    {
        if(get_user_id()>0)
        {
            $receipt = self::getOrCreateByUser(get_user_id());
        }else 
        {
            $uid = sfContext::getInstance()->getUser()->getAttribute("anonimus_user_uid");
            if( strlen($uid) < 1 )
            {
                return null;
            }else 
            {
                $receipt = self::getOrCreateByAnonymousUid($uid);
            }
        }
        if($receipt == null)
            return false;
        else
        return true;
    }
    public static function getOrCreateByUser($userId)
    {
            $c = new Criteria();
            $c->add(ReceiptPeer::USER_ID, $userId);
            $c->add(ReceiptPeer::STATUS_ID, MyConstants::STATUS_NEW);
            $cart= ReceiptPeer::doSelectOne($c);
            if( empty($cart ))
            {
                $cart = new Receipt();
                $cart->setUserId($userId);
                $cart->setStatusId(MyConstants::STATUS_NEW);
                $cart->save();
            }
        return $cart;
    }
    public static function recalculate($id)
    {
        $c = new Criteria();
        $c->add(ReceiptItemPeer::RECEIPT_ID, $id);
        
        $arReceiptItems = ReceiptItemPeer::doSelect($c);
        
        //debugvar($receipt);
        $itemsQnt = 0;
        $receiptItemsQnt = 0;
        $totalPrice = 0;
        if (!empty($arReceiptItems))
        {

            foreach ( $arReceiptItems as $item )
            {
                $itemsQnt = $itemsQnt + $item->getQuantity();
                $receiptItemsQnt++;
                $totalPrice = $totalPrice + ($item->getQuantity() * $item->getPriceOfItem());
            }
            /*$c = new Criteria();
            $c->add(ReceiptPeer::ID, $id);
            $receipt = ReceiptPeer::doSelectOne($c);*/

        }
        $receipt = ReceiptPeer::retrieveByPK($id);
        if (!empty($receipt))
        {
            $receipt->setReceiptItemsQnt($receiptItemsQnt);
            $receipt->setTotalPrice($totalPrice);
            $receipt->setItemsQnt($itemsQnt);
            $receipt->save();
        }
    }
}
